import React, { useMemo, useState } from 'react'

/**
 * 
 * @returns 
 * useMemo如何优化？ 简单理解就是对传入的这个函数的返回值做优化。返回值可以是任意~~数组/数字/对象/数组
 * useMemo返回的也是一个memoized（记忆的）值；
 * 在依赖不变的情况下，多次定义的时候，返回的值是相同的；
 */

function calcNumber(count) {
  console.log('calcNumber计算了');
  let total = 0;
  for (let i = 1; i <= count; i++) {
    total += i;
  }
  return total
}

export default function MemoHookDemo() {
  const [count, setCount] = useState(10);
  const [show, setShow] = useState(false)
  
  // const total = calcNumber(count);

  const total = useMemo(() => {
    return calcNumber(count)
  }, [count]);

  return (
    <div>
      <h2>当前计数：{total}</h2>
      <button onClick={e => setCount(count + 1)}>+1</button>
      
      <button onClick={e => setShow(!show)}>show/hide</button>
    </div>
  )
}
